package org.infosys.org.service.impl;

import org.apache.commons.mail.EmailException;
import org.infosys.basic.exception.BusinessException;
import org.infosys.basic.utils.BaiduAuditUtils;
import org.infosys.basic.utils.SendEmailUtils;
import org.infosys.org.domain.Employee;
import org.infosys.org.domain.Shop;
import org.infosys.org.domain.ShopAuditLog;
import org.infosys.org.mapper.EmployeeMapper;
import org.infosys.org.mapper.ShopAuditLogMapper;
import org.infosys.org.mapper.ShopMapper;
import org.infosys.org.service.IShopService;
import org.infosys.basic.service.impl.BaseServiceImpl;
import org.infosys.org.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hank
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;


    /**
    * @Title: loadById
    * @Description: 驳回后根据邮箱链接跳转回显
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 23:20
    * @Parameters: [id]
    * @Return org.infosys.org.domain.Shop
    */
    @Override
    public Shop loadById(Long id) {
        Shop shop = shopMapper.loadById(id);
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        shop.setAdmin(employee);
        return shop;
    }

    /**
    * @Title: settlement
    * @Description: 店铺入驻
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/1 20:18
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        // 判读字段非空
        if (ObjectUtils.isEmpty(shop.getName()) | ObjectUtils.isEmpty(shop.getAddress()) | ObjectUtils.isEmpty(shop.getTel())) {
            throw new BusinessException("参数不能为空! 请重新注册");
        }
        // 用百度AI检测店铺和管理员名字是否合规
        if (!BaiduAuditUtils.TextCensor(shop.getName()) || !BaiduAuditUtils.TextCensor(shop.getAdmin().getUsername())) {
            throw new BusinessException("有违规敏感词汇，请重新修改");
        }
        // 检测电话和邮箱是否真实

        // 根据传入的管理员信息查询员工
        Employee empTemp = employeeMapper.loadByName(shop.getAdmin().getUsername());
        // 判断数据库中是否已经存在该管理员
        if (!ObjectUtils.isEmpty(empTemp)) {
            // 根据员工的id查询店铺
            Shop shopTemp = shopMapper.loadById(empTemp.getShopId());
            // 店铺不为空, 判断店铺的状态
            if (!ObjectUtils.isEmpty(shopTemp)) {
                    // 状态为1,管理了已经通过审核的店铺
                    if(shopTemp.getState().equals(1)) {
                        throw new BusinessException("已经管理了店铺,不能重复注册");
                    } else { // 状态不为1，表示驳回后，修改信息重新提交了，修改店铺的状态为待审核
                        shopTemp.setState(0);
                        shopMapper.update(shopTemp);
                        employeeMapper.update(shop.getAdmin());
                    }
            } else if (empTemp.getState().equals(-2)) {
                throw new BusinessException("该管理员已被限制!禁止注册");
            } else { // 员工注册过，但是没有管理店铺,可以注册
                // 先保存店铺信息
                shop.setAdminId(empTemp.getId());
                shopMapper.save(shop);
                // 再修改员工信息
                shop.getAdmin().setId(empTemp.getId());
                shop.getAdmin().setShopId(shop.getId());
                employeeMapper.update(shop.getAdmin());
            }
        } else {// 此时没有问题，店铺员工都需要重新注册
            // 新增店铺状态为待审核
            shop.setState(0);
            shopMapper.save(shop);
            shop.getAdmin().setShopId(shop.getId());
            employeeMapper.save(shop.getAdmin());
            shop.setAdminId(shop.getAdmin().getId());
            shopMapper.update(shop);
        }
    }

    /**
    * @Title: loadShopEcharsData
    * @Description: 店铺状态报表数据
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 10:47
    * @Parameters: []
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> loadShopEcharsData() {
        List<ShopVo> shopVos = shopMapper.loadShopEcharsData();
        List<Integer> states = shopVos.stream().map(ShopVo::getState).collect(Collectors.toList());
        List<Integer> y = shopVos.stream().map(ShopVo::getCountNum).collect(Collectors.toList());
        List<String> x = new ArrayList<>();
        for (Integer state: states) {
            if (state.equals(0)) {
                x.add("待审核");
            }
            if (state.equals(1)) {
                x.add("激活");
            }
            if (state.equals(-1)) {
                x.add("驳回");
            }
            if (state.equals(2)) {
                x.add("待激活");
            }
            if (state.equals(-2)) {
                x.add("拒绝");
            }
        }
        HashMap<String, Object> data = new HashMap<>();
        data.put("x",x);
        data.put("y",y);
        return data;
    }

    /**
    * @Title: pass
    * @Description: 店铺通过
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 15:43
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    @Transactional
    public void pass(ShopAuditLog shopAuditLog) throws EmailException {

        Shop shopTemp = shopMapper.loadById(shopAuditLog.getShopId());
        shopTemp.setState(2);
        // 修改店铺的状态
        shopMapper.update(shopTemp);

        shopAuditLog.setAuditTime(new Date());
        // 没有登录功能，默认写死
        shopAuditLog.setAuditId(88L);
        // 插入日志
        shopAuditLogMapper.save(shopAuditLog);
        // 发送激活邮件给用户
        // 目标邮箱
        Employee employeeTemp = employeeMapper.loadById(shopTemp.getAdminId());
        // 主题
        String title = "店铺审核结果通知";
        // 链接
        String text = "您的店铺已通过审核，请点击下面链接激活店铺" + "修改链接：http://127.0.0.1:8081/#/login?id=" + shopAuditLog.getShopId();
        String email = employeeTemp.getEmail();
        SendEmailUtils.sendMail(email, title, text);
    }

    /**
    * @Title: audit
    * @Description: 店铺激活
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 22:27
    * @Parameters: [id]
    * @Return void
    */
    @Override
    @Transactional
    public void audit(Long id) {
        Shop shop = shopMapper.loadById(id);
        // 修改状态
        shop.setState(1);
        shopMapper.update(shop);
    }

    /**
    * @Title: reject
    * @Description: 店铺驳回
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 22:38
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    @Transactional
    public void reject(ShopAuditLog shopAuditLog) throws EmailException {

        Shop shopTemp = shopMapper.loadById(shopAuditLog.getShopId());
        shopTemp.setState(-1);
        // 修改店铺的状态
        shopMapper.update(shopTemp);

        shopAuditLog.setAuditTime(new Date());
        // 没有登录功能，默认写死
        shopAuditLog.setAuditId(88L);
        // 插入日志
        shopAuditLogMapper.save(shopAuditLog);
        // 目标邮箱
        Employee employeeTemp = employeeMapper.loadById(shopTemp.getAdminId());
        // 主题
        String title = "店铺审核结果通知";
        // 链接
        String text = "您的店铺审核未通过，原因：" + shopAuditLog.getNote() + " 修改链接：http://127.0.0.1:8081/#/shopRegisterAgain?shopId=" + shopAuditLog.getShopId();
        SendEmailUtils.sendMail(employeeTemp.getEmail(), title, text);
    }

    /**
    * @Title: refuse
    * @Description: 拒绝通过
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/3 23:31
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    @Transactional
    public void refuse(ShopAuditLog shopAuditLog) throws EmailException {
        Shop shopTemp = shopMapper.loadById(shopAuditLog.getShopId());
        // 修改店铺的状态为拒绝状态
        shopTemp.setState(-2);
        shopMapper.update(shopTemp);
        Employee employeeTemp = employeeMapper.loadById(shopTemp.getAdminId());
        // 修改管理员的状态为禁用
        employeeTemp.setState(0);
        employeeMapper.update(employeeTemp);
        shopAuditLog.setAuditTime(new Date());
        // 没有登录功能，默认写死
        shopAuditLog.setAuditId(88L);
        // 插入日志
        shopAuditLogMapper.save(shopAuditLog);
        // 主题
        String title = "店铺审核结果通知";
        // 链接
        String text = "您已被限制开店，原因：" + shopAuditLog.getNote();
        SendEmailUtils.sendMail(employeeTemp.getEmail(), title, text);
    }

    /**
    * @Title: batchSave
    * @Description: 批量保存
    * @Author: hank
    * @Version: 1.0
    * @Date:  2022/7/5 17:49
    * @Parameters: [shops]
    * @Return void
    */
    @Override
    public void batchSave(List<Shop> shops) {
        shopMapper.batchSave(shops);
    }
}
